var sw=20,//方块的宽度
    sh=20,//方块的高度
    tr=30,//行数
    td=30;//列数

var snake = null;//蛇的实例
var food = null;//蛇的实例
var game = null;//游戏实例


//方块构造函数
function Square(x,y,classname){
    this.x=x*sw;
    this.y=y*sh;
    this.classname = classname;
    this.viewContent = document.createElement('div');//方块对应的DOM元素
    this.viewContent.className = this.classname;
    this.parent = document.getElementById('snakeWrap');//方块的父级
}
Square.prototype.create = function(){//创建方块DOM
    this.viewContent.style.position = 'absolute';
    this.viewContent.style.width = sw + 'px';
    this.viewContent.style.height = sh + 'px';
    this.viewContent.style.left = this.x + 'px';
    this.viewContent.style.top = this.y + 'px';
    this.parent.appendChild(this.viewContent);
}
Square.prototype.remove = function(){
    this.parent.removeChild(this.viewContent);
}


//蛇的构造函数
function Snake(){
    this.head = null;//存一下蛇头的信息
    this.tail = null;//存一下蛇尾的信息
    this.pos = [];//存蛇身上所有方块的位置
    this.directionNum = {//存储蛇走的方向，用一个对象来表示
        left:{
            x:-1,
            y:0,
            rotate:180 //蛇头的旋转度数
        },
        right:{
            x:1,
            y:0,
            rotate:0
        },
        up:{
            x:0,
            y:-1,
            rotate:-90
        },
        down:{
            x:0,
            y:1,
            rotate:90
        }
    }
}
//初始化方法
Snake.prototype.init = function(){
    //创建蛇头
    var snakeHead = new Square(2,0,'snakeHead');
    snakeHead.create();
    this.head =snakeHead;  //存储蛇头信息
    this.pos.push([2,0]);  //存储蛇头位置

    //创建蛇身体1
    var snakeBody1 = new Square(1,0,'snakeBody');
    snakeBody1.create();
    this.pos.push([1,0]); //蛇身1 的坐标存起来

    //创建蛇身体2
    var snakeBody2 = new Square(0,0,'snakeBody');
    snakeBody2.create();
    this.tail = snakeBody2; //把蛇尾的信息存起来
    this.pos.push([0,0]); //蛇身2 的坐标存起来

    //形成链表关系
    snakeHead.last = null;
    snakeHead.next = snakeBody1;
    snakeBody1.last = snakeHead;
    snakeBody1.next = snakeBody2;
    snakeBody2.last = snakeBody1;
    snakeBody2.next = null;

    //给蛇添加一条属性，用来表示蛇走的方向
    this.direction = this.directionNum.right;
}

//这个方法用来获取蛇头的下一个位置对应的元素，要根据元素做不同的事情
Snake.prototype.getNextPos = function(){
    var nextPos = [
        this.head.x/sw + this.direction.x,
        this.head.y/sh + this.direction.y
    ]

    //下个点是自己，代表撞到了自己，游戏结束！
    selfCollied = false;
    this.pos.forEach(function(value){
        if(value[0]==nextPos[0]&&value[1]==nextPos[1]){
            selfCollied = true;
        }
    })
    if(selfCollied){
        console.log("撞到了自己");

        this.strategies.die.call(this);
        return;
    }

    //下个点是围墙，代表撞到了围墙，游戏结束1
    if(nextPos[0]<0||nextPos[1]<0||nextPos[0]>td-1||nextPos[1]>tr-1){
        console.log("撞到了墙");

        this.strategies.die.call(this);
        return;
    }

    //下个点是苹果，吃，增长
    if(food && food.pos[0]==nextPos[0]&&food.pos[1]==nextPos[1]){
        console.log("撞到食物了");
        this.strategies.eat.call(this);
        return;
    }
    
    //下个点是空，走
    this.strategies.move.call(this);

}

//处理碰撞后要做的事情
Snake.prototype.strategies = {
    move:function(format){ //这个参数决定要不要删去蛇尾，用户未传参数为走
        //创建一个新的身体(在旧蛇头的位置)
        var newBody  = new Square(this.head.x/sw,this.head.y/sh,'snakeBody');
        //更新链表的关系
        newBody.next = this.head.next;
        newBody.next.last = newBody;
        newBody.last = null;

        this.head.remove();//把旧蛇头删除
        newBody.create();

        //创建新的蛇头(蛇头碰撞点)
        var newHead = new Square(this.head.x/sw + this.direction.x,this.head.y/sh + this.direction.y,'snakeHead');
        newHead.create();
        //更新链表
        newHead.next = newBody;
        newHead.last = null;
        newBody.last = newHead;
        newHead.viewContent.style.transform='rotate('+this.direction.rotate+'deg)';

        //蛇身上每一个点的坐标更新
        this.pos.splice(0,0,[this.head.x/sw + this.direction.x,this.head.y/sh + this.direction.y]);
        this.head = newHead;//更新this.head

        if(!format){//format为0，表示需要删除蛇尾
            this.tail.remove();
            this.tail = this.tail.last;

            this.pos.pop();//删除数组
        }

    },
    //吃苹果
    eat:function(){
        this.strategies.move.call(this,true);
        createFood();
        game.score++;
    },
    die:function(){
        console.log('die');
        game.over();
    }
}

//初始化蛇
snake = new Snake();

//创建食物
function createFood(){
    //食物小方块的随机坐标
    var x = null;
    var y = null;

    var include = true; //循环跳出的条件，true 表示食物的坐标在蛇身上，false表示食物的坐标不在蛇身上
    while(include){
        x = Math.round(Math.random()*(td-1));
        y = Math.round(Math.random()*(tr-1));

        snake.pos.forEach(function(value){
            if(x!=value[0] && y!=value[1]){
                //这个条件说明食物不在蛇身上，但我个人觉得“&&” 可以写成“||”-->有待验证

                include = false;
            }
        })    
    }

    //生成食物
    food = new Square(x,y,'food');
    food.pos=[x,y];//存储生成食物的坐标
    var foodDom = document.querySelector('.food');
    if(foodDom){
        foodDom.style.left = x*sw + 'px';
        foodDom.style.top = y*sh + 'px';
    }else{
        food.create();
    }
    
}



//创建游戏逻辑
function Game(){
    this.timer = null;
    this.score = 0;
}
Game.prototype.init=function(){
    snake.init();
    createFood();
    document.onkeydown = function(ev){
        if(ev.key=='ArrowLeft' && snake.direction != snake.directionNum.right){
            snake.direction = snake.directionNum.left;
        }else if(ev.key=='ArrowUp' && snake.direction != snake.directionNum.down){
            snake.direction = snake.directionNum.up;
        }else if(ev.key=='ArrowRight' && snake.direction != snake.directionNum.left){
            snake.direction = snake.directionNum.right;
        }else if(ev.key=='ArrowDown' && snake.direction != snake.directionNum.up){
            snake.direction = snake.directionNum.down;
        }
    }
    this.start();
}
//开始游戏
Game.prototype.start = function(){
    this.timer = setInterval(function(){
        snake.getNextPos();
    },400)
}
//结束游戏
Game.prototype.over = function(){
    clearInterval(this.timer);
    alert('你的得分为'+this.score);

    //游戏回到最初是的状态
    var snakeWrap = document.getElementById('snakeWrap');
    snakeWrap.innerHTML = '';
    snake = new Snake();
    game = new Game();
    var startBtnWrap = document.querySelector('.startBtn');
    startBtnWrap.style.display = 'block';
}
//暂停游戏
Game.prototype.pause=function(){
    clearInterval(this.timer);
}
//开启游戏
game = new Game();
var startBtn = document.querySelector('.startBtn button');
startBtn.onclick = function(){
    startBtn.parentNode.style.display = 'none';
    game.init();
} 
//暂停以及重启游戏
var snakeWrap = document.getElementById('snakeWrap');
var pauseBtn = document.querySelector('.pauseBtn button');
snakeWrap.onclick=function(){
    game.pause();
    pauseBtn.parentNode.style.display='block';
}
pauseBtn.onclick = function(){
    game.start();
    pauseBtn.parentNode.style.display='none';
}